const fs = require('fs');
const { v4: uuidv4 }= require('uuid');

function uuid() {
    return uuidv4().replace(/-/g, '')
}


function readConfig(fileName){
    var configFilePath = __dirname + '/../../data/' + fileName;
    console.log('configFilePath', configFilePath)
    if(fs.existsSync(configFilePath)){
        try {
            return {success: true, data: fs.readFileSync(configFilePath)};
        } catch (e) {
            return {success: false, error: e};
        }
    } else {
        return {success: false, error: '文件不存在！'}
    }
}

function readJsonConfig(fileName) {
    var result = readConfig(fileName);
    if(result.success) {
        try {
            return eval("(" + result.data +")")
        } catch (error) {
            console.log("转换配置为json对象失败！" + error);
        }
        return {};
    } else {
        console.log("读取配置文件失败！" + result.error);
        return {}
    }
}

var cache = {
}

function readJsonConfigCache(fileName) {
   if(!cache[fileName]) {
        cache[fileName] = readJsonConfig(fileName);
    }
    return cache[fileName];
}

/**
 * 获取异常错误信息
 * 
 * @param {*} error 
 * @returns 
 */
function extractErrorInfo(error) {
    if(error.message) {
        return error.message;
    } else{
        return JSON.stringify(error);
    }
}

module.exports = {
    uuid: uuid,
    readJsonConfig: readJsonConfig,
    readJsonConfigCache: readJsonConfigCache,
    extractErrorInfo: extractErrorInfo,
    readConfig: readConfig
}


